<?php

namespace App\Http\Controllers;

use App\Models\Regsettings;
use App\Repositories\RegsettingsRepository;
use App\Http\Requests\Logic\Regsettings\QueryResource;
use App\Http\Requests\Logic\Regsettings\RegsettingsUpdate;

/**
 * Date: 28/04/2018
 * @author George
 * @package App\Http\Controllers
 */
class RegsettingsController extends Controller
{
    protected $regsettingsRepository;

	/**
	 * RegsettingsController constructor.
	 * @param RegsettingsRepository $regsettingsRepository
	 */
    public function __construct(
        RegsettingsRepository $regsettingsRepository
    )
    {
        $this->regsettingsRepository = $regsettingsRepository;
    }

    /**
     * 获取注册设置资源
     *
     * Date: 2018/4/20
     * @author Tenny
     * @param QueryResource $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(QueryResource $request)
    {
        $company_id = $request->get('company_id', false);
        $regsettings = $this->regsettingsRepository->getRegSettings($company_id);
        $res_arr = $regsettings->toArray();
        if (is_array($res_arr) && count($res_arr) > 0 )
        {
            unset($res_arr);
            return success($regsettings);
        } else {
            //不存在数据插入一条数据  注册设置都为默认值
            $regsettings = new Regsettings;
            $regsettings->company_id = $company_id;
            $regsettings->save();
            $res = $regsettings->toArray();
            if (isset($res['company_id']))
            {
                $company_id = $res['company_id'];
                $regsettings = $this->regsettingsRepository->getRegSettings($company_id);
                return success($regsettings);
            } else{
                return failed('未知错误', 500);
            }
        }
    }

	/**
	 * 更新注册设置资源
	 *
	 * Date: 28/04/2018
	 * @author George
	 * @param RegsettingsUpdate $request
	 * @param Regsettings $regsetting
	 * @return \Illuminate\Http\JsonResponse
	 */
    public function update(RegsettingsUpdate $request, Regsettings $regsetting)
    {
        $regsettingsAttr = $request->only([
            'stature',
            'education',
            'marital',
            'address'.
            'urgency',
            'trade',
            'skill',
            'channel',
        ]);
        $regsetting->update($regsettingsAttr);
        return updated($regsetting);
    }
}
